import fs from 'fs';
import path from 'path';

/**
 * 自动生成侧边栏配置
 * @param {string} docsDir - 文档根目录
 * @param {string} currentDir - 当前目录
 * @returns {Array} 侧边栏配置数组
 */
function generateSidebar(docsDir, currentDir = '') {
  const sidebar = [];
  const fullPath = path.join(docsDir, currentDir);

  // 读取目录下的文件和子目录
  const files = fs.readdirSync(fullPath);

  // 先处理README.md
  if (files.includes('README.md')) {
    sidebar.push({
      text: currentDir ? currentDir.split('/').pop().charAt(0).toUpperCase() + currentDir.split('/').pop().slice(1) : 'API 文档',
      link: currentDir ? `/${currentDir}/README.md` : '/api/README.md'
    });
  }

  // 处理其他md文件
  const mdFiles = files.filter(file => file.endsWith('.md') && file !== 'README.md');
  mdFiles.forEach(file => {
    const fileName = file.replace('.md', '');
    sidebar.push({
      text: fileName.charAt(0).toUpperCase() + fileName.slice(1),
      link: currentDir ? `/${currentDir}/${file}` : `/${file}`
    });
  });

  // 处理子目录
  const subDirs = files.filter(file => {
    const filePath = path.join(fullPath, file);
    return fs.statSync(filePath).isDirectory() && file !== '.vitepress';
  });

  subDirs.forEach(subDir => {
    const subDirPath = currentDir ? `${currentDir}/${subDir}` : subDir;
    const subSidebar = generateSidebar(docsDir, subDirPath);

    if (subSidebar.length > 0) {
      sidebar.push({
        text: subDir.charAt(0).toUpperCase() + subDir.slice(1),
        items: subSidebar,
        collapsed: true
      });
    }
  });

  return sidebar;
}

export default generateSidebar;